package com.baizhi.springboot.realm;

import com.baizhi.springboot.entity.Admin;
import com.baizhi.springboot.entity.Role;
import com.baizhi.springboot.service.AdminService;
import com.baizhi.springboot.service.Resourceservice;
import com.baizhi.springboot.service.RoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private Resourceservice resourceservice;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取当前用户
        String username = (String) principals.getPrimaryPrincipal();
        //获取用户信息
        Admin admin = adminService.selectByName(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //获得角色名字
        Set<String> roleName=roleService.selectRoleNameByUserId(admin.getId());
        //获得角色id set集合
        Set<String> roleId = roleService.selectRoleIdByUserId(admin.getId());
        simpleAuthorizationInfo.setRoles(roleName);
        System.out.println(admin+"+++++++++++"+roleId+"*********");
        //获得权限
        Set<String> stringPermssions=resourceservice.selectResourceByRoles(roleId);
        System.out.println(stringPermssions);
        simpleAuthorizationInfo.setStringPermissions(stringPermssions);

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username= ((UsernamePasswordToken)token).getUsername();
        Admin admin = adminService.selectByName(username);
        return new SimpleAuthenticationInfo(admin.getUsername(),admin.getPassword(),getName());
    }
}
